﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using JiebaNet.Segmenter;
using Microsoft.Office.Interop.Word;
using Task = Microsoft.Office.Interop.Word.Task;

namespace QBWeb.Models
{
    public  class WordTools
    {
        /// <summary>
        /// 获取word文本
        /// </summary>
        /// <param name="pathName"></param>
        /// <returns></returns>
        public  string GetText(string pathName)
        {
            //实例化COM
            var wordApp = new ApplicationClass();
            object fileObj = pathName;
            //System.Reflection.Missing.Value是System.Reflection.Missing类的唯一实例，作为缺省值参数传给word对象的某个函数
            object nullObj = System.Reflection.Missing.Value;
            //打开指定文件（不同版本的COM参数个数有差异，一般而言除第一个外都用nullobj就行了）
            var doc = wordApp.Documents.Open(
                ref fileObj, ref nullObj, ref nullObj,
                ref nullObj, ref nullObj, ref nullObj,
                ref nullObj, ref nullObj, ref nullObj,
                ref nullObj, ref nullObj, ref nullObj,
                ref nullObj, ref nullObj, ref nullObj,
                ref nullObj
            );
            //取得doc文件中的文本
            var outText = doc.Content.Text;
            //关闭文件
            doc.Close(ref nullObj, ref nullObj, ref nullObj);
            //关闭COM
            wordApp.Quit(ref nullObj, ref nullObj, ref nullObj);

            //删除文件 线程模式，异步运行
            var task = new Task<int>(() =>
            {
                File.Delete(pathName);
                return 1;
            });
            task.Start();
            
            //返回
            return outText;
        }
       
    }
    

    public  class GetSeg
    {
        private const string Pattern1 = @"(\r\n)*[\s\S]*?(\r\n){2,}";
        private const string Pattern2 = @"\d{1,}分";
        private const string Pattern3 = @"[错对]";
        private const string Pattern4 = @"(\r\n)*[\s\S]*?(\r\n){1,}";
        /// <summary>
        /// 识别
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public  Dictionary<int, Dictionary<string, string>> CutText(string text)
        {
            var seg = new JiebaSegmenter();
            //seg.AddWord("(错)", 1000, "n");
            //上面无法添加新词字典，貌似不支持特殊字符和中文的组合；

            var dicDic = new Dictionary<int, Dictionary<string, string>>();

            var i = 0;
            string[] typeQuest = { "单选题", "判断题", "填空题", "多选题", "简答题", "综合题" };
            foreach (Match match in Regex.Matches(text, Pattern1)) //划分每道题
            {
                var keyWords = seg.Cut(match.Value).ToList();
                //提取关键词，获取长度大于等于3的关键词并去重
                var arrayStr =String.Join(",", keyWords
                    .Where(keyWord => keyWord.Length > 2)
                    .Where(keyWord => !typeQuest.Contains(keyWord))
                    .Distinct().ToArray());

                if (match.Value.Contains("(错)")|| match.Value.Contains("(对)")|| match.Value.Contains("（对）")|| match.Value.Contains("（错）"))  //根据正确答案判断是否是判断题// 扩大容错率
                {
                    dicDic.Add(i, TrueFalse(match.Value,arrayStr)); 
                    i++;
                }
                else if (keyWords.Contains("单选题"))
                {
                    dicDic.Add(i, SingleChoice(match.Value, arrayStr));
                    i++;
                }
                else if (keyWords.Contains("填空题"))
                {
                    dicDic.Add(i, Blank(match.Value, arrayStr));
                    i++;
                }
            }
            return dicDic;
        }

        /// <summary>
        /// 判断题
        /// </summary>
        /// <param name="match"></param>
        /// <param name="keyWordList"></param>
        /// <returns></returns>
        private static Dictionary<string, string> TrueFalse(string match,string keyWordList)
        {
            var dict = new Dictionary<string, string> {["type"] = "2"};
            string newText;
            if (Regex.IsMatch(match, Pattern2)) //判断是否有分值
            {
                //这里分值是用来组卷的，如果单纯入库的话没有用
                var score = Matches(match, Pattern2);
                dict["score"] = score.Replace("分", ""); //去掉分值
                newText = match.Replace(score, "").Replace("[", "").Replace("]", ""); //移除分值
            }
            else
            {
                newText = match;
                dict["score"] = "5";  //默认5分
            }
            var correctValue = Matches(match, Pattern3); //第二次匹配正确答案
            dict["correct"] = correctValue;
            //移除正确值
            newText = newText.Replace(correctValue, "").Replace("（", "").Replace("）", "");
            dict["quest"] = newText.Replace("\r\n",""); //字典保存题
            dict["keyWords"] = keyWordList;
            return dict;
        }

        /// <summary>
        /// 单选题
        /// </summary>
        /// <param name="match"></param>
        /// <param name="keyWordList"></param>
        /// <returns></returns>
        private static Dictionary<string, string> SingleChoice(string match,string keyWordList)
        {
            var dict = new Dictionary<string, string> {["type"] = "1"};
            var options = (from Match match2 in Regex.Matches(match, Pattern4) select match2.Value).ToList(); //分离题干选项

            dict["correct"] = Matches(options[0], @"（.*）|\(.*\)")
                .Replace("(","")
                .Replace(")","")
                .Replace("（", "")
                .Replace("）", "")
                .Replace("　", ""); //匹配正确选项

            var score = Matches(options[0], Pattern2); //匹配分数
            dict["score"] = score.Replace("分", "");

            options[0] = options[0]
                .Replace(score, "")
                .Replace("[", "")
                .Replace("]", "")
                .Replace("单选题", "")
                .Replace(dict["correct"], ""); //移除分值&题型

            dict["quest"] = options[0].Replace("\r\n", "");
            for (var k = 1; k < options.Count(); k++)
            {
                var analysis = Matches(options[k], @"答案解析"); //查看有无答案解析
                if (analysis != "答案解析")
                {
                    var optionChar = Matches(options[k], @"[A-Z]."); //获取选项的对应选项字母，比如 [A.水] 得到A. 
                    options[k] = options[k].Replace(optionChar, "");//提取选项值
                    //optionChar = optionChar.Replace(".", ""); //去掉点
                    //dict["optionChar" + k] = optionChar;
                    dict["option" + k] = options[k].Replace("\r\n", "");
                    dict["analysis"] = "";
                }
                else
                {
                    dict["analysis"] = options[k].Replace("\r\n", "");
                }
            }
            dict["keyWords"] = keyWordList;
            return dict;
        }

        /// <summary>
        /// 填空题
        /// </summary>
        /// <param name="match"></param>
        /// <param name="keyWordList"></param>
        /// <returns></returns>
        private static Dictionary<string, string> Blank(string match, string keyWordList)
        {
            var dict = new Dictionary<string, string> { ["type"] = "3" };
            var score = Matches(match, Pattern2);
            //var blanks = new List<string>(); 
            var blanks = "";
            var temp = match;
            var count = 1;//计数器
            var x = Regex.Matches(match, @"{.*?}");
            foreach (Match match2 in x)
            {
                if(count==x.Count)
                  blanks += (match2.Value.Replace("{", "")
                    .Replace("}", ""));
                else
                {
                    blanks += (match2.Value.Replace("{", "")
                            .Replace("}", "")) + ",";  //正确答案英文逗号隔开
                }
                temp = temp.Replace(match2.Value, "____");
                count++;
            }

            dict["blanks"] = blanks.Trim();
            dict["score"] = score.Replace("分", "");
            dict["quest"] = temp.Replace(score, "")
                .Replace("[", "").Replace("]", "")
                .Replace("填空题", "")
                .Replace("\r\n", ""); 
            dict["keyWords"] = keyWordList;
            return dict;
        }
        /// <summary>
        /// 正则函数
        /// </summary>
        /// <param name="input"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        private static string Matches(string input, string pattern)
        {
            var text = "";
            foreach (Match match in Regex.Matches(input, pattern))
            {
                text = match.Value;
            }
            return text;
        }

    }
}









#region 待使用功能
    //else if (words.Contains("多选题"))
    //{
    //    tempDict["type"] = "多选题";
    //    List<string> options = new List<string>();
    //    foreach (Match match2 in Regex.Matches(match.Value, Pattern4)) //划分一道题内的选项
    //    {
    //        options.Add(match2.Value);
    //    }

    //    tempDict["correct"] = Matches(options[0], @"（.*?）").Replace("（", "").Replace("）", "")
    //        .Replace("　", ""); //匹配正确选项
    //    var score = Matches(options[0], Pattern2);
    //    tempDict["score"] = score.Replace("分", "");

    //    options[0] = options[0].Replace(score, "").Replace("[", "").Replace("]", "").Replace("多选题", "")
    //        .Replace(tempDict["correct"], ""); //移除分值

    //    tempDict["quest"] = options[0];
    //    for (int k = 1; k < options.Count(); k++)
    //    {
    //        tempDict["option" + k] = options[k];
    //    }

    //    items.Add(i, tempDict);
    //    i++;
    //}
    //else if (words.Contains("不定项题"))
    //{
    //    tempDict["type"] = "不定项题";
    //    List<string> options = new List<string>();
    //    foreach (Match match2 in Regex.Matches(match.Value, Pattern4)) //划分一道题内的选项
    //    {
    //        options.Add(match2.Value);
    //    }

    //    tempDict["correct"] = Matches(options[0], @"（.*?）").Replace("（", "").Replace("）", "")
    //        .Replace("　", ""); //匹配正确选项
    //    var score = Matches(options[0], Pattern2);
    //    tempDict["score"] = score.Replace("分", "");

    //    options[0] = options[0].Replace(score, "").Replace("[", "").Replace("]", "").Replace("不定项题", "")
    //        .Replace(tempDict["correct"], ""); //移除分值

    //    tempDict["quest"] = options[0];
    //    for (int k = 1; k < options.Count(); k++)
    //    {
    //        tempDict["option" + k] = options[k];
    //    }

    //    items.Add(i, tempDict);
    //    i++;
    //}
    //else if (words.Contains("简答题"))
    //{
    //    tempDict["type"] = "简答题";
    //    var score = Matches(match.Value, Pattern2);
    //    tempDict["score"] = score.Replace("分", "");
    //    tempDict["quest"] = match.Value.Replace(score, "").Replace("[", "").Replace("]", "")
    //        .Replace("简答题", ""); //移除分值

    //    items.Add(i, tempDict);
    //    i++;
    //}

#endregion